package br.com.lh.ura.database;

import java.sql.SQLException;
import java.util.Map;

import javax.servlet.ServletContext;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import flex.messaging.FlexContext;

public class DBConnection {

    protected final ServletContext panelContext;

    protected final UraTransaction uraTransaction;

    public DBConnection() throws SQLException, ClassNotFoundException {
	ServletContext thisContext = FlexContext.getServletContext();
	panelContext = thisContext.getContext("/PabxManagement");
	WebApplicationContext springContext = WebApplicationContextUtils
		.getWebApplicationContext(thisContext);
	uraTransaction = (UraTransaction) springContext.getBean("uraTransaction");
    }

    public String saveUra(UraXml uraView, String sessionId) throws Exception {
	return uraTransaction.saveUra(uraView, getCompanyId(sessionId));
    }

    @SuppressWarnings("unchecked")
    protected Integer getCompanyId(String sessionId) {
	Map<String, String> map = (Map<String, String>) panelContext.getAttribute("sessionMap");
	String companyId = map.get(sessionId);
	return Integer.valueOf(companyId);
    }

    public UraXml loadUra(String uraId, String sessionId) {
	UraXml loadUra = uraTransaction.loadUra(Integer.valueOf(uraId), getCompanyId(sessionId));
	return loadUra;
    }

    public UraResource getUraResource(String sessionId) {
	return uraTransaction.loadUraResources(getCompanyId(sessionId));
    }

}
